package com.xzp.gkrpc;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ServiceDescriptor {
    private String clazz;
    private String method;
    private String returnTypes;
    private String[] parameterType;

    /**
     * 根据类与方法构造ServiceDescriptor对象
     * @param clazz
     * @param method
     * @param <T>
     * @return
     */
    public static <T> ServiceDescriptor from(Class<T> clazz, Method method){
        ServiceDescriptor descriptor = new ServiceDescriptor();
        descriptor.setClazz(clazz.getName());
        descriptor.setMethod(method.getName());
        descriptor.setReturnTypes(method.getReturnType().getName());
        Class<?>[] parameterTypes = method.getParameterTypes();
        String[] ptString = new String[parameterTypes.length];
        for(int i=0; i<parameterTypes.length; i++){
            ptString[i] = parameterTypes[i].getName();
        }
        descriptor.setParameterType(ptString);
        return descriptor;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ServiceDescriptor that = (ServiceDescriptor) o;
        return Objects.equals(clazz, that.clazz) && Objects.equals(method, that.method) && Objects.equals(returnTypes, that.returnTypes) && Arrays.equals(parameterType, that.parameterType);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(clazz, method, returnTypes);
        result = 31 * result + Arrays.hashCode(parameterType);
        return result;
    }

}
